package com.scujj.cs6.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scujj.cs6.mapper.UserFollowMapper;
import com.scujj.cs6.model.entity.UserFollow;
import com.scujj.cs6.model.vo.UserFanVo;
import com.scujj.cs6.model.vo.UserFollowVo;
import com.scujj.cs6.service.UserFollowService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author FlanChan
 * @description 针对表【user_follow】的数据库操作Service实现
 * @createDate 2025-03-25 21:21:24
 */
@Service
@AllArgsConstructor
public class UserFollowServiceImpl extends ServiceImpl<UserFollowMapper, UserFollow>
        implements UserFollowService {

    @Override
    public void followUser(Long id, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("user");
        if (userId.equals(id)) {
            throw new RuntimeException("不能关注自己");
        }
        if (this.count(new LambdaQueryWrapper<>(UserFollow.class).eq(UserFollow::getUserId, userId).eq(UserFollow::getFollowUserId, id)) > 0) {
            throw new RuntimeException("已关注");
        }
        UserFollow userFollow = new UserFollow();
        userFollow.setUserId(userId);
        userFollow.setFollowUserId(id);
        this.save(userFollow);
    }

    @Override
    public void cancelFollow(Long id, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("user");
        if (userId.equals(id)) {
            throw new RuntimeException("不能取消关注自己");
        }
        if (this.count(new LambdaQueryWrapper<>(UserFollow.class).eq(UserFollow::getUserId, userId).eq(UserFollow::getFollowUserId, id)) == 0) {
            throw new RuntimeException("未关注");
        }
        this.remove(new LambdaQueryWrapper<>(UserFollow.class).eq(UserFollow::getUserId, userId).eq(UserFollow::getFollowUserId, id));
    }

    @Override
    public List<UserFollowVo> getFollowList(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("user");
        return this.baseMapper.selectFollowListByUserId(userId);
    }

    @Override
    public List<UserFanVo> getFansList(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("user");
        return this.baseMapper.selectFanListByUserId(userId);
    }

    @Override
    public Boolean isFollow(HttpServletRequest request) {
        return this.count(new LambdaQueryWrapper<>(UserFollow.class).eq(UserFollow::getUserId, request.getAttribute("user"))) > 0;
    }
}




